﻿/*
创建人：zhangrj
日期：2022-05-23
描述：排产下发页面js
*/
var page = {
    url: getRootPath() + "/Ashx/ApsHandler/ApsPlanDownSendHandler.ashx", //后台处理url,
    commonUrl: getRootPath() + "/Ashx/CommonHandler.ashx", //通用方法后台路径
    //分页参数
    pagetotal: 0,
    pageSize: 50,
    pageNumber: 1,
    apsPlanDetailDatas: [], //编辑弹窗选择的主数据
    diffTimes: 0, //排产开始时间和结束时间差值
    init: function () {
        page.bind();
        page.bindWorkCenter();
        NewcustomizedEasyuiPagination('pp'); //定制化分页
        $('#pp').find('.pageSize').val(page.pageSize); //初始化行数
        page.bindUserRole();
    },
    //绑定事件
    bind: function () {
        //列表加载
        $("#gdApsPlanInfo").datagrid({
            onLoadSuccess: function (data) {
                $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: page.pagetotal,
                    pageSize: page.pageSize,
                    pageNumber: page.pageNumber
                });
                NewcustomizedEasyuiPagination('pp'); //定制化分页
            },
            columns: [[
        { field: 'ck', title: '选择', checkbox: true },
        { field: 'MFGORDERNAME', title: '订单号', width: 120 },
        { field: 'TEAMNAME', title: '件号主制单元', width: 120 },
        { field: 'CONTAINERNAME', title: '批次', width: 150 },
        { field: 'DESCRIPTION', title: '零件名称', width: 100 },
        { field: 'QTY', title: '在制数', width: 50 },
        { field: 'APSQTY', title: '排产数', width: 50 },
        { field: 'RESOURCENAME', title: '设备编码', width: 100 },
        {
            field: 'RESOURCEDESC', title: '设备名称', width: 100,
            styler: function (value, row, index) { if (row.PRODUCTLINE != "" && row.PRODUCTLINE != null) { return 'background-color:#ffee00;color:red;'; } },
            formatter: function (value, row, index) {
                if (row.PRODUCTLINE != "" && row.PRODUCTLINE != null) {
                    var name = value + "(" + row.CUSTOMOBJECTITEMSNAME + ")"
                    if (row.STATE != null) {
                        name += row.STATE == "1" ? "待执行" : (row.STATE == "2" ? "执行中" : (row.STATE == "3" ? "已完成" : (row.STATE == "4" ? "已撤销" : "已报废")))
                    }
                    return name;
                } else { return value; }
            } //add by longb 2024-04-02
        },
        { field: 'APSPLANEMPNAME', title: '人员', width: 100 },
        { field: 'WORKFLOWINFO', title: '工艺', width: 170 },
        { field: 'WORKFLOWNAME', title: '工艺', width: 150, hidden: true },
        { field: 'SPECNO', title: '工序号', width: 60, hidden: true },
        { field: 'WORKFLOWSTEPNAME', title: '排产工序', width: 150 },
        { field: 'CONTAINERTYPENAME', title: '批次类型', width: 80 },
        { field: 'APSTYPENAME', title: '排产策略', width: 70 },
        {
            field: 'STARTTIME', title: '排产开始时间', width: 130,
            formatter: function (value, row, index) {
                if (!isNullOrWhiteSpaceStr(value)) {
                    return dayjs(value).format('YYYY-MM-DD HH:mm');
                }
            }
        },
        {
            field: 'ENDTIME', title: '排产结束时间', width: 130,
            formatter: function (value, row, index) {
                if (!isNullOrWhiteSpaceStr(value)) {
                    return dayjs(value).format('YYYY-MM-DD HH:mm');
                }
            }
        },
        { field: 'DOWNFULLNAME', title: '下发人', width: 80 },
        { field: 'DOWNTIME', title: '下发时间', width: 150 },
        { field: 'REASON', title: '原因', width: 150 },
        { field: 'REMARK', title: '备注', width: 150 },
        { field: 'log', title: '日志查看', width: 150, formatter: function (value, row, index) {
            if(row.LOGCOUNT>0){
            return "<button   class='' onclick=page.LookLogData('" + row.APSPLANDETAILID + "') style='cursor:pointer;width: 70px; height: 22px'>查看</button>";
        } }
        }
      ]]
        });
        $("#gdMakeEmployee").datagrid({
            onLoadSuccess: function (data) {
                for (var i = 0; i < data.rows.length; i++) {
                    if (data.rows[i].checked == true) {
                        $(this).datagrid('checkRow', i);
                    }
                }
            },
            columns: [[
        { field: 'ck', title: '选择', checkbox: true },
        { field: 'EMPLOYEENAME', title: '员工号', width: 100 },
        { field: 'FULLNAME', title: '姓名', width: 100 },
        { field: 'EMPLOYEEID', title: 'EMPLOYEEID', hidden: true }
      ]]
        });
        //列表分页事件
        $('#pp').pagination({
            onSelectPage: function (pageNumber, pageSize) {
                NewcustomizedEasyuiPagination('pp'); //定制化分页
                page.pageSize = pageSize; page.pageNumber = pageNumber;
                page.search();
            }
        });
        //查询信息
        $("#btnSearch").on("click", function () {
            page.reset(false, true, true);
            page.pageNumber = 1;
            page.search();
        });
        //重置查询
        $("#btnReset").on("click", function () {
            page.reset(true, true, true);
        });
        //下发
        $("#btnSend").on("click", function () {
            clearMessage();
            page.planSend();
        });

        // 下发派工&发布到看板
        $("#btnSendDispatchAndDashboard").on("click", function () {
            clearMessage();
            var resObj = page.isVaildRows(1);
            if (!resObj.result) {
                displayMessage(resObj.msg, false);
                return;
            }
           if(resObj.datas.length==1&&dayjs(dayjs(resObj.datas[0].STARTTIME).format('YYYY-MM-DD')) <dayjs(dayjs().format('YYYY-MM-DD')).add(4, 'day')){
               $('#ReasonForm').form('load',{
                    mfgordername:resObj.datas[0].MFGORDERNAME,
                    containername:resObj.datas[0].CONTAINERNAME,
                    starttime:resObj.datas[0].STARTTIME,
                    description:resObj.datas[0].DESCRIPTION,
                    workflowstepname:resObj.datas[0].WORKFLOWSTEPNAME,
                    endtime:resObj.datas[0].ENDTIME,
                    qty:resObj.datas[0].QTY,
                    accept:true
                });
              $("#dgReason").dialog({modal: true});
           }else{
              page.sendDownApsPlanDatas(resObj.datas,"","");
           }
        });

        //回收
        $("#btnReCall").on("click", function () {
            clearMessage();
            page.planReCall();
        });
        //删除
        $("#btnDele").on("click", function () {
            clearMessage();
            page.planDele();
        });
        //下发到手动排产
        $("#btnSendHand").on("click", function () {
            clearMessage();
            page.planSendHand();
        });
        //编辑排产数据
        $("#btnEditApsResult").on("click", function () {
            clearMessage();
            page.openEditApsData(1);
        });
        //批量编辑排产数据
        $("#btnBatchEditApsResult").on("click", function () {
            clearMessage();
            page.openEditApsData(2);
        });
        //保存（窗体）
        $("#btnSave").on("click", function () {
            page.saveApsData();
        });
        //关闭（窗体）
        $("#btnClose").on("click", function () {
            $("#dg").dialog("close");
        });
        //状态下拉事件
        $('#selStatus').combobox({
            valueField:'value',
            textField:'text',
            value:'1',
            data:[{value:'0',text:'未下发'},{value:'1',text:'已下发'},{value:'5',text:'下发审批中'},{value:'6',text:'回收审批中'}],
            onSelect: function (record) {
                if (record.value === "0") {//未下发
                    clearEasyuiDataGrid("gdApsPlanInfo");
                    $("#divSend").hide();
                    $("#divDele").show();
                    //$("#divEditResult").show();
                    $("#divReCall").hide();
                    $("#divSendDown,#divEditResult,#divBatchEditResult").show(); //add by longb 2024-04-03
                    $("#divSendDownBack,#divSendDownBack1").hide(); //add by longb 2024-04-03
                    $("#divSendDispatchAndDashboard").show();
                    $("#divAgreeSendDown,#divRefuseSendDown,#divAgreeReCall,#divReason").hide();
                } else if(record.value === "1") {//已下发
                    clearEasyuiDataGrid("gdApsPlanInfo");
                    $("#divSend").hide();
                    $("#divDele").hide();
                    //$("#divEditResult").hide();
                    $("#divReCall").show();
                    $("#divSendDown").hide(); //add by longb 2024-04-03
                    $("#divSendDownBack,#divSendDownBack1,#divEditResult,#divBatchEditResult").show(); //add by longb 2024-04-03
                    $("#divSendDispatchAndDashboard").hide();
                    $("#divAgreeSendDown,#divRefuseSendDown,#divAgreeReCall,#divReason").hide();
                }else if(record.value === "5"){
                    clearEasyuiDataGrid("gdApsPlanInfo");
                    $("#divAgreeSendDown,#divRefuseSendDown,#divReason").show();
                    $("#divSend,#divDele,#divReCall,#divSendDown,#divSendDownBack,#divSendDownBack1,#divSendDispatchAndDashboard,#divEditResult,#divBatchEditResult,#divAgreeReCall").hide();
                }else{
                    clearEasyuiDataGrid("gdApsPlanInfo");
                    $("#divAgreeReCall,#divRefuseSendDown,#divReason").show();
                    $("#divSend,#divDele,#divReCall,#divSendDown,#divSendDownBack,#divSendDownBack1,#divSendDispatchAndDashboard,#divEditResult,#divBatchEditResult,#divAgreeSendDown").hide();
                }

                if(record.value === "5"){
                    $('#gdApsPlanInfo').datagrid('showColumn','DOWNFULLNAME');
                    $('#gdApsPlanInfo').datagrid('showColumn','DOWNTIME');
                    $('#gdApsPlanInfo').datagrid('showColumn','REASON');
                    $('#gdApsPlanInfo').datagrid('showColumn','REMARK');
                }else{
                    $('#gdApsPlanInfo').datagrid('hideColumn','DOWNFULLNAME');
                    $('#gdApsPlanInfo').datagrid('hideColumn','DOWNTIME');
                    $('#gdApsPlanInfo').datagrid('hideColumn','REASON');
                    $('#gdApsPlanInfo').datagrid('hideColumn','REMARK');
                }
            }
        });

        //绑定分页go按钮
        $('#pageGo').on("click", function () {
            clearMessage();
            var pageNumber = Number($(this).parents('tr').find('.pagination-num').val());
            page.pageSize = $('#pp').find('.pageSize').val() == "" ? 50 : Number($('#pp').find('.pageSize').val());
            page.pageNumber = pageNumber;
            page.search();
        });
        //排产开始日期选择后事件
        $("#txtStartDate").datetimebox({
            onHidePanel: function () {
                var start = dayjs($("#txtStartDate").datetimebox("getValue")).format('YYYY-MM-DD HH:mm:ss');
                if(start === "Invalid Date")
                {
                    return;
                }
                if(page.diffTimes === 0)
                {
                    $("#txtResStartDate").datetimebox("setValue", start);
                    return;
                }
                var lastEnd = dayjs(start).add(page.diffTimes, 'second').format('YYYY-MM-DD HH:mm:ss');
                $("#txtEndDate").datetimebox("setValue", lastEnd); //更新排产结束日期，根据期量随之变动
                //更新设备日期
                $("#txtResStartDate").datetimebox("setValue", start);
                $("#txtResEndDate").datetimebox("setValue", lastEnd);
            }
        });
        //排产结束日期选择后事件
        $("#txtEndDate").datetimebox({
            onHidePanel: function () {
                var end = dayjs($("#txtEndDate").datetimebox("getValue")).format('YYYY-MM-DD HH:mm:ss');
                if(end === "Invalid Date")
                {
                    return;
                }
                if(page.diffTimes === 0)
                {
                    $("#txtResEndDate").datetimebox("setValue", end);
                    return;
                }
                var lastStart = dayjs(end).subtract(page.diffTimes, 'second').format('YYYY-MM-DD HH:mm:ss');
                $("#txtStartDate").datetimebox("setValue", lastStart); //更新排产开始日期，根据期量随之变动
                //更新设备日期
                $("#txtResStartDate").datetimebox("setValue", lastStart);
                $("#txtResEndDate").datetimebox("setValue", end);
            }
        });

        //同意下发按钮操作
        $("#btnAgreeSendDown").on("click", function () {
            //$("#btnSendDispatchAndDashboard").click();
            var rows = $("#gdApsPlanInfo").datagrid('getChecked'); //获取勾选的行
            var reason=$("#inputReason").textbox("getValue");
            page.sendDownApsPlanDatas(rows,reason,"");
        });
        //同意回收按钮操作
        $("#divAgreeReCall").on("click", function () {
          var rows = $("#gdApsPlanInfo").datagrid('getChecked'); //获取勾选的行
            var reason=$("#inputReason").textbox("getValue");
           page.ReCall(rows,reason,"");
        });
    },
    bindUserRole:function(){
        page.post(page.url, { action: "GetUserRole" }, true, function (res) {
            if(res.Result){
                $('#selStatus').combobox("setValue","5")
              }
                $("#reason").combobox({
                    valueField: 'CUSTOMOBJECTITEMSDESC',
                    textField: 'CUSTOMOBJECTITEMSDESC',
                    panelHeight: 200,
                    data: res.DBTable //下拉数据
                });
        });
    },
    //绑定工区
    bindWorkCenter: function () {
        page.post(page.commonUrl, { action: "GetWorkcenterOfDefault" }, true, function (res) {
            //绑定查询工区下拉框
            var workCenter = res.DBTable;
            workCenter.splice(0, 0, { WORKCENTERNAME: "请选择", WORKCENTERID: "", NOTES: null, WCTYPE: null });
            $("#selWorkCenter").combobox({
                valueField: 'WORKCENTERID',
                textField: 'WORKCENTERNAME',
                panelHeight: 200,
                data: workCenter, //res.DBTable, //下拉数据
                onSelect: function (record) {
                    page.bindTeam(record.WORKCENTERID, 1); //加载班组
                }
            });
            if (res.ReturnData != null) {
                $("#selWorkCenter").combobox("setValue", res.ReturnData); //默认值      
            }
            //绑定弹窗工区下拉框
            $("#ddlWorkcenter").combobox({
                valueField: 'WORKCENTERID',
                textField: 'WORKCENTERNAME',
                panelHeight: 200,
                data: res.DBTable, //下拉数据
                onSelect: function (record) {
                    page.bindTeam(record.WORKCENTERID, 2); //加载班组
                }
            });
        });
    },
    //绑定查询班组(type:1,查询，2,弹窗)
    bindTeam: function (workCenterId, type) {
        page.post(page.commonUrl, { action: "GetTeam", workCenterId: workCenterId }, false, function (res) {
            if (type === 1) {
                //绑定班组
                $("#selTeam").combobox({
                    valueField: 'TEAMID',
                    textField: 'TEAMNAME',
                    panelHeight: 200,
                    data: res.DBTable //下拉数据
                });
                // 件号主制单元
                $("#ddlProductTeam").combobox({
                    valueField: 'TEAMID',
                    textField: 'TEAMNAME',
                    panelHeight: 200,
                    data: res.DBTable //下拉数据
                });
                if (res.ReturnData != null) {
                    $("#selTeam").combobox("setValue", res.ReturnData); //默认值      
                }
            }
            else {
                //绑定班组
                $("#ddlTeam").combobox({
                    valueField: 'TEAMID',
                    textField: 'TEAMNAME',
                    panelHeight: 200,
                    data: res.DBTable //下拉数据
                });
            }
        });
    },
    //查询
    search: function () {
        clearEasyuiDataGrid("gdApsPlanInfo");
        var params = [{
            mfgOrderName: $("#txtOrderNum").textbox("getValue"), //订单号
            containerName: $("#txtContainerNum").textbox("getValue"), //批次号
            productName: $("#txtProductNum").textbox("getValue"), //件号
            specNo: $("#txtSpecNo").textbox("getValue"), //工序号
            startTime1: $("#txtPlanStartTime1").datebox("getValue"), //开始时间
            startTime2: $("#txtPlanStartTime2").datebox("getValue"), //开始时间
            endTime1: $("#txtPlanEndTime1").datebox("getValue"), //结束时间
            endTime2: $("#txtPlanEndTime2").datebox("getValue"), //结束时间
            apsType: $("#selApsType").combobox("getValue"), //排产策略
            workCenter: $("#selWorkCenter").combobox("getValue"), //工区
            team: $("#selTeam").combobox("getValue"), //班组
            status: $("#selStatus").combobox("getValue"), //下发状态
            state: $("#selState").combobox("getValue"), //是否产线工序 add by longb 2024-04-03
            productteamid: $("#ddlProductTeam").combobox("getValue"), //件号主制单元
            resourceCode: $("#txtResourceCode").textbox("getValue")//设备编码
        }];
        var formData = {
            pageSize: page.pageSize,
            pageNumber: page.pageNumber,
            action: "GetApsPlanListByPage",
            params: JSON.stringify(params)
        };
        page.post(page.url, formData, true, function (res) {
            page.pagetotal = res.RowCount;
            $("#gdApsPlanInfo").datagrid('loadData', { total: res.RowCount, rows: res.DBTable });
        });
    },
    //下发
    planSend: function () {
        var res = page.isVaildRows(1);
        if (!res.result) {
            displayMessage(res.msg, false);
            return;
        }
        page.post(page.url, { action: "SaveApsPlanDatas", type: "Send", datas: JSON.stringify(res.datas) }, true, function (res) {
            if (res.Result) {
                page.search();
            }
            displayMessage(res.Message, res.Result);
        });
    },
    //回收
    planReCall: function () {
        var resObj = page.isVaildRows(2);
        if (!resObj.result) {
            displayMessage(resObj.msg, false);
            return;
        }
        if(resObj.datas.length==1&&dayjs(dayjs(resObj.datas[0].STARTTIME).format('YYYY-MM-DD')) <dayjs(dayjs().format('YYYY-MM-DD')).add(4, 'day')){
               $('#ReasonForm').form('load',{
                    mfgordername:resObj.datas[0].MFGORDERNAME,
                    containername:resObj.datas[0].CONTAINERNAME,
                    starttime:resObj.datas[0].STARTTIME,
                    description:resObj.datas[0].DESCRIPTION,
                    workflowstepname:resObj.datas[0].WORKFLOWSTEPNAME,
                    endtime:resObj.datas[0].ENDTIME,
                    qty:resObj.datas[0].QTY,
                    accept:true
                });
              $("#dgReason").dialog({modal: true});
           }else{
           page.ReCall(resObj.datas,"","");
        }
       
    },
    ReCall:function(rows,reason,remark){
            var status=$("#selStatus").combobox("getValue"); //下发状态
            page.post(page.url, { action: "SaveApsPlanDatas", type: "ReCall",status:status,reason:reason,remark:remark, datas: JSON.stringify(rows) }, true, function (res) {
            if (res.Result) {
                page.search();
                page.clearForm();
                $("#inputReason").textbox("setValue",'');
            }
            displayMessage(res.Message, res.Result);
            });
    },
    //删除
    planDele: function () {
        var res = page.isVaildRows(3);
        if (!res.result) {
            displayMessage(res.msg, false);
            return;
        }
        page.post(page.url, { action: "SaveApsPlanDatas", type: "Dele",status:"", datas: JSON.stringify(res.datas) }, true, function (res) {
            if (res.Result) {
                page.search();
            }
            displayMessage(res.Message, res.Result);
        });
    },
    //下发到手动排产
    planSendHand: function () {
        var res = page.isVaildRows(4);
        if (!res.result) {
            displayMessage(res.msg, false);
            return;
        }
        page.post(page.url, { action: "SendHandApsDatas", datas: JSON.stringify(res.datas) }, true, function (res) {
            if (res.Result) {
                page.search();
            }
            displayMessage(res.Message, res.Result);
        });
    },
    //编辑排产数据
    openEditApsData: function (type) {
        page.apsPlanDetailDatas = [];
        clearMessage();
        var rows = $("#gdApsPlanInfo").datagrid('getChecked');
        if (rows.length === 0) {
            displayMessage("请选择数据", false);
            return;
        }
        if (type === 1 && rows.length !== 1) {
            displayMessage("请选择单条数据", false);
            return;
        }
        if (type === 2 && rows.length < 2) {
            displayMessage("请选择多条数据", false);
            return;
        }
        //重构页面勾选的数据
        page.apsPlanDetailDatas = rows.map(function (item) {
            return {
                apsplandetailid: item.APSPLANDETAILID,
                workflowid: item.WORKFLOWID,
                workflowstepid: item.WORKFLOWSTEPID,
                specid: item.SPECID,
                containerid:item.CONTAINERID,
                type: type
            }
        });
        var formData = {
            action: "GetEditApsPlanResultDialogData",
            apsPlanDetailDatas: JSON.stringify(page.apsPlanDetailDatas)
        };
        page.post(page.url, formData, true, function (data) {
            if (!data.Result) {
                displayMessage(data.Message, false);
                return;
            }
            page.clearDialogPage();
            var employeeIDs = [];
            for (var i = 0; i < data.DBDataSet.dtEmp.length; i++) {
                employeeIDs.push(data.DBDataSet.dtEmp[i].EMPLOYEEID);
            }
            $("#ddlResource").combobox({
                valueField: 'RESOURCEID',
                textField: 'RESOURCENAME',
                panelHeight: 200,
                data: data.DBDataSet.dtRes, //下拉数据
                onSelect: function (record) {
                    page.bindResEmployee(record.RESOURCEID, employeeIDs); //绑定设备人员
                }
            });
            $("#txtResStartDate").datetimebox('disable');
            $("#txtResEndDate").datetimebox('disable');
            var status = $("#selStatus").combobox("getValue");
            if (status == 1) { //已下发
                $("#txtStartDate").datetimebox('disable'); //禁止编辑排产开始日期
                $("#txtEndDate").datetimebox('disable'); //禁止编辑排产结束日期
            }
            else {
                $("#txtStartDate").datetimebox({ disable: false }); //启用编辑排产开始日期
                $("#txtEndDate").datetimebox({ disable: false }); //禁用编辑排产结束日期
            }
            if (type === 1) { //如果只选择一条数据，则绑定相对应数据
                $("#divApsPlanQty").show();
                $("#ddlResource").combobox('setValue', rows[0].RESOURCEID);
                $("#ddlWorkcenter").combobox("setValue", rows[0].WORKCENTERID);
                $("#ddlTeam").combobox("setValue", rows[0].TEAMID);
                $("#txtApsPlanQty").numberbox("setValue", rows[0].APSQTY);

                if (rows[0].STARTTIME != null && rows[0].ENDTIME != null) {
                    var start = dayjs(rows[0].STARTTIME).format('YYYY-MM-DD HH:mm:ss');
                    var end = dayjs(rows[0].ENDTIME).format('YYYY-MM-DD HH:mm:ss');
                    page.diffTimes = dayjs(end).diff(start, "second");
                }
                if (rows[0].STARTTIME != null) {
                    $("#txtStartDate").datetimebox("setValue", dayjs(rows[0].STARTTIME).format('YYYY-MM-DD HH:mm:ss'));
                }
                if (rows[0].ENDTIME != null) {
                    $("#txtEndDate").datetimebox("setValue", dayjs(rows[0].ENDTIME).format('YYYY-MM-DD HH:mm:ss'));
                }
                //设备日期绑定
                if (rows[0].RESSTARTTIME != null) {
                    $("#txtResStartDate").datetimebox("setValue", dayjs(rows[0].RESSTARTTIME).format('YYYY-MM-DD HH:mm:ss'));
                }
                if (rows[0].RESENDTIME != null) {
                    $("#txtResEndDate").datetimebox("setValue", dayjs(rows[0].RESENDTIME).format('YYYY-MM-DD HH:mm:ss'));
                }
            }
            else {
                $("#divApsPlanQty").hide(); //批量编辑，隐藏排产数
                var resorce = rows.filter((item, index, arr) =>
                      arr.findIndex(t => t.RESOURCEID === item.RESOURCEID) === index
                    );
                if (resorce.length == 1) {
                    $("#ddlResource").combobox('setValue', rows[0].RESOURCEID);
                }
                var workcenter = rows.filter((item, index, arr) =>
                      arr.findIndex(t => t.WORKCENTERID === item.WORKCENTERID) === index
                    );
                if(workcenter.length==1){
                    $("#ddlWorkcenter").combobox("setValue", rows[0].WORKCENTERID);
                }
                var team = rows.filter((item, index, arr) =>
                      arr.findIndex(t => t.TEAMID === item.TEAMID) === index
                    );
                if(team.length==1){
                    $("#ddlTeam").combobox("setValue", rows[0].TEAMID);
                }
            }
            //打开弹窗
            $("#dg").dialog({
                onClose: function () { //关闭事件，恢复主页面按钮
                    $("#mainDiv").find(".easyui-linkbutton").each(function () {
                        $(this).linkbutton('enable');
                    });
                }
            });
            //禁用主页面所有按钮
            $("#mainDiv").find(".easyui-linkbutton").each(function () {
                $(this).linkbutton('disable');
            });
        });
    },
    //绑定设备人员
    bindResEmployee: function (resourceID, employeeIDs) {
        clearEasyuiDataGrid("gdMakeEmployee", 1);
        page.post(page.url, { action: "GetResEmployee", resourceId: resourceID }, true, function (data) {
            if (employeeIDs === undefined || employeeIDs === null) {
                $("#gdMakeEmployee").datagrid('loadData', { rows: data });
                return;
            }
            var newData = [];
            data.forEach(function (e) {
                if (employeeIDs.indexOf(e.EMPLOYEEID) != -1) {
                    e.checked = true;
                }
                newData.push(e);
            });
            $("#gdMakeEmployee").datagrid('loadData', { rows: newData });
        });
    },
    //保存排产数据
    saveApsData: function () {
        var isValid = $("#ff").form('validate');
        if (!isValid) {
            $.messager.alert('错误', "请填写必填项", 'error');
            return false;
        }
        var resEmp = $("#gdMakeEmployee").datagrid('getChecked');
        if (resEmp.length === 0) {
            $.messager.alert('错误', "请选择人员", 'error');
            return false;
        }
        var formData = $("#ff").serializeArray();
        var param = {
            resStartDate: $("#txtResStartDate").datetimebox('getValue'),
            resEndDate: $("#txtResEndDate").datetimebox('getValue'),
            startDate: $("#txtStartDate").datetimebox('getValue'),
            endDate: $("#txtEndDate").datetimebox('getValue'),
            status: $("#selStatus").combobox("getValue")
        }
        $.each(formData, function () {
            param[this.name] = this.value;
        });
        if (page.apsPlanDetailDatas[0].type === 2) {//如果是批量编辑，删除排产数
            delete param.apsPlanQty;
        }
        var postData = {
            action: "IsSureSaveApsPlanDetail",
            apsPlanDetailDatas: JSON.stringify(page.apsPlanDetailDatas),
            param: JSON.stringify(param),
            resEmp: JSON.stringify(resEmp)
        };
        //先验证，在保存
        page.post(page.url, postData, true, function (res) {
            if (!res.Result) {
                if (res.ReturnData === "1") {
                    $.messager.confirm('确认', res.Message, function (r) {
                        if (r) {
                            page.saveApsData2(postData);
                        }
                    });
                } else {
                    $.messager.alert('错误', res.Message, 'error');
                }

            } else {
                page.saveApsData2(postData);
            }
        });
    },
    saveApsData2: function (postData) {
        postData.action = "SaveApsPlanDetailData";
        page.post(page.url, postData, true, function (res) {
            if (res.Result) {
                displayMessage(res.Message, true, true);
                page.search();
            }
            else {
                displayMessage(res.Message, false, true);
            }
        });
    },
    //清除弹窗页面数据
    clearDialogPage: function () {
        clearEasyuiDataGrid("gdMakeEmployee", 1);
        $("#ddlResource").combobox('setValue', "");
        $("#ddlWorkcenter").combobox("setValue", "");
        $("#ddlTeam").combobox("setValue", "");
        $("#ddlTeam").combo("panel").empty();
        $("#txtApsPlanQty").numberbox("setValue", "");
        $("#txtStartDate").datetimebox("setValue", "");
        $("#txtEndDate").datetimebox("setValue", "");
        $("#txtResStartDate").datetimebox("setValue", "");
        $("#txtResEndDate").datetimebox("setValue", "");
    },
    //验证选择数据，返回验证对象（type=1：下发，2：回收，3：删除，4：下发到手动排产）
    isVaildRows: function (type) {
        var res = { result: true, msg: "", datas: [] }; //验证返回对象
        var rows = $("#gdApsPlanInfo").datagrid('getChecked'); //获取勾选的行
        if (rows.length === 0) {
            res.result = false;
            res.msg = "未选择数据";
            return res;
        }
        //    if (type === 1) { //如果是下发，则需要验证是否存在多种策略
        //        var newRows = rows;
        //        var isVaild = true;
        //        for (var i = 0; i < rows.length; i++) {
        //            if (!res.result) {
        //                break;
        //            }
        //            for (var j = 0; j < newRows.length; j++) {
        //                if (rows[i].CONTAINERID === newRows[j].CONTAINERID && rows[i].APSTYPE !== newRows[j].APSTYPE) {
        //                    res.result = false;
        //                    res.msg = "所选批次号：" + rows[i].CONTAINERNAME + "存在多种排产策略";
        //                    break;
        //                }
        //            }
        //        }
        //    }
        if(type === 1||type === 2){
            for (var i = 0; i < rows.length; i++) {
                if(dayjs(dayjs(rows[i].STARTTIME).format('YYYY-MM-DD')) <dayjs(dayjs().format('YYYY-MM-DD')).add(4, 'day')){
                    res.result = false;
                    res.msg = "所选批次号：" + rows[i].CONTAINERNAME + "在未来3天往前范围内，禁止批量操作";
                    break;
                }
            }
            if(rows.length==1){
                res.result = true;
            }
        }
        if (res.result) {
            res.datas = rows;
        }
        return res;
    },
    //post数据（路径，参数，是否异步，成功返回方法）
    post: function (url, param, async, callback) {
        $.ajax({
            type: "Post",
            url: url,
            data: param,
            cashe: false,
            async: async,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                $.messager.progress('close');
                callback(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                displayMessage(XMLHttpRequest.responseText, false);
            }
        });
    },
    //清除方法，重要！！！
    reset: function (iscondition, isresult, isDetail) {
        clearMessage();
        if (iscondition) {
            $("#txtOrderNum").textbox("setValue", ""); //订单号
            $("#txtContainerNum").textbox("setValue", ""); //批次号
            $("#txtProductNum").textbox("setValue", ""); //件号
            $("#txtPlanStartTime").textbox("setValue", ""); //排产开始时间
            $("#txtPlanEndTime").textbox("setValue", ""); //排产结束时间
            $("#txtSpecNo").textbox("setValue", ""); //工序号
            $("#selApsType").combobox("setValue", ""); //排产策略
            $("#selStatus").combobox("setValue", "0"); //下发状态
            $("#selState").combobox("setValue", "") //是否产线工序 add by longb 2024-04-03
            page.bindWorkCenter();
        }

        if (isresult) {
            clearEasyuiDataGrid("gdApsPlanInfo", 1); //查询结果列表
            page.pageNumber = 1; page.pagetotal = 0; //重置分页
            $('#pp').pagination('refresh', {
                total: page.pagetotal,
                pageSize: page.pageSize,
                pageNumber: page.pageNumber
            });
        }
    },
    ///下发工序任务到产线 add by longb 2024-04-03
    sendDownOrderTaskToFms: function () {
        var rows = $("#gdApsPlanInfo").datagrid('getChecked'); //获取勾选的行
        var ids = [];
        var datas = [];
        $.each(rows, function (index, item) {
            if (item.PRODUCTLINE != null && (item.STATE == null || item.STATE == "4" || item.STATE == "5")) {//未下发、已撤销、已报废
                ids.push(item.APSPLANDETAILID);
                datas.push(item);
            }
        });
        if (ids.length == 0) {
            displayMessage("请选择需要下发产线执行的工序数据信息再进行操作", false);
            return;
        }
        $.messager.confirm('提示', "确认下发任务到产线系统吗？", function (r) {
            if (r) {
                page.post(getRootPath() + "/Ashx/ProductLinesHandler.ashx", { action: "sendDownOrderTaskToFms", type: "Send", apsplandetailids: ids.join(','), datas: JSON.stringify(datas) }, true, function (res) {
                    if (res.Result) {
                        page.search();
                    }
                    displayMessage(res.Message, res.Result);
                });
            }
        });
    },
    //下发产线工序任务（撤销、作废） add by longb 2024-04-03
    sendDownOrderTaskToFmsBack: function (type) {
        var rows = $("#gdApsPlanInfo").datagrid('getChecked'); //获取勾选的行
        var ids = [];
        var datas = [];
        $.each(rows, function (index, item) {
            if (item.PRODUCTLINE != null && (item.STATE == "1")) {//待执行
                ids.push(item.APSPLANDETAILID);
                datas.push(item);
            }
        });

        if (ids.length == 0) {
            displayMessage("请选择【待执行】的工序数据信息再进行操作", false);
            return;
        }
        $.messager.confirm('提示', "确认【" + (type == 4 ? "撤销" : "报废") + "】已下发的工序任务吗？", function (r) {
            if (r) {
                page.post(getRootPath() + "/Ashx/ProductLinesHandler.ashx", { action: "specstatusChange", type: type, apsplandetailids: ids.join(','), datas: JSON.stringify(datas) }, true, function (res) {
                    if (res.Result) {
                        page.search();
                    }
                    displayMessage(res.Message, res.Result);
                });
            }
        });
    },
    //审核--拒绝下发或回收
    refuseSendDown:function(){
        var rows = $("#gdApsPlanInfo").datagrid('getChecked'); //获取勾选的行
        if (rows.length == 0) {
            displayMessage("请选择工序数据信息再进行操作", false);
            return;
        }
        var status=$("#selStatus").combobox("getValue")=="5"?0:1; //下发状态
        var reason=$("#inputReason").textbox("getValue");
        if(reason==''){
            displayMessage("请输入原因", false);
            return;
        }
        page.post(page.url, { action: "RefuseSendDown",status:status,reason:reason,datas: JSON.stringify(rows) }, true, function (res) {
            if (res.Result) {
                page.search();
                $("#inputReason").textbox("setValue","");
            }
            displayMessage(res.Message, res.Result);
        });
    },
    LookLogData:function(id){
         page.post(page.url, { action: "GetDownLogData",id:id }, true, function (res) {
            if (res.Result) {
               $("#dgLogTable").datagrid('loadData', res.DBTable );
               $("#dgLog").dialog({modal: true});
            }
        });
    },
    sendDownApsPlanDatas:function(rows,reason,remark){
        var status=$("#selStatus").combobox("getValue"); //下发状态
            $.messager.confirm('确认', '你确认要【下发派工&发布到看板】吗?', function (r) {
                if (!r) { return; }
                page.post(page.url, { action: "SaveApsPlanDatas", type:"Send",status:status,datas: JSON.stringify(rows),reason:reason,remark:remark }, true, function (res) {
                    if (res.Result) {
                        $("#inputReason").textbox("setValue",'');
                        page.post(page.url, { action: "SendHandApsDatas", datas: JSON.stringify(rows) }, true, function (res) {
                            if (res.Result) {
                                displayMessage('【下发派工&发布到看板】成功', true);
                                page.search();
                                page.clearForm();
                                return;
                            } else {
                                return displayMessage(res.Message, res.Result);
                            }
                        });
                    } else {
                        return displayMessage(res.Message, res.Result);
                    }
                })
            });
    },
    submitForm:function(){
        var reason=$("#reason").combobox("getValue"); //原因
        var remark=$("#remark").textbox("getValue"); //备注
        var status=$("#selStatus").combobox("getValue"); //下发状态
        if(reason==''){
            displayMessage("请选择原因", false);
                return;
        }
        var rows = $("#gdApsPlanInfo").datagrid('getChecked'); //获取勾选的行
        if(status=="0"){
            page.sendDownApsPlanDatas(rows,reason,remark);
        }else{
          page.ReCall(rows,reason,remark);
        }
    },
    clearForm:function(){
        $('#ReasonForm').form('clear');
        $("#dgReason").dialog('close');
    }
}
$(function () {
  page.init();
})
